<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Proxy\TokenProxy;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Overtrue\LaravelSocialite\Socialite;
use ThrottlesLogins;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    protected $proxy;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(TokenProxy $proxy)
    {
        $this->middleware('guest')->except('logout');
        $this->proxy = $proxy;
    }

    public function login(Request $request)
    {
//        if ($this->hasTooManyLoginAttempts($request)) {
//            $this->fireLockoutEvent($request);
//            return $this->sendLockoutResponse($request);
//        }
        return $this->proxy->login(request('mobile'), request('password'));
    }

    public function logout()
    {
        return $this->proxy->logout();
    }

    public function refresh()
    {
        return $this->proxy->refresh();
    }

    public function threelogin($type)
    {
        return Socialite::driver($type)->redirect();
    }
    public function threeredirect($type)
    {
        $user = Socialite::driver($type)->user();
        $auth['type'] = $type;
        $auth['openid'] = $user->getId();
        $userinfo = \App\User::where($type.'openid', $user->getId())->first();
        if ($userinfo) {
            $auth['data'] = $this->proxy->proxy('password', [
                'username' => $userinfo->mobile,
                'password' => $userinfo->password,
                'scope'    => '',
            ]);
        }
        //判断此QQ或者微信是否被绑定
        $auth['nickname']=$user->getNickname();
        $auth['avatar'] =$user->getAvatar();
        $hashtoken = md5($user->getId());
        Redis::setex($hashtoken,120,json_encode($auth));
        if(request('bind')==1) {
            //个人中心绑定成功跳转地址
            return redirect('/userCore?activeName=setting&hashtoken='.$hashtoken);
        }
        //前台三方登录成功跳转地址
        return redirect('/?hashtoken='.$hashtoken);
    }

    public function threecallback($hashtoken){
        $auth = json_decode(Redis::get($hashtoken),true);
        if(isset($auth['data'])){
            return $auth['data'];
        }
        return $auth;
    }

}
